package com.aaa.arouterone.testViewModel

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.aaa.arouterone.R
import com.alibaba.android.arouter.facade.annotation.Route
import kotlinx.android.synthetic.main.activity_for_view_model.*

/**
 *   viewmodel 测试学习
 *  @author lfc-LFC
 *  created at 2021/3/30 17:24
 */
@Route(path = "/app/mainVM")
class ActivityForViewModelA : AppCompatActivity() {
    val vm2: com.aaa.arouterone.testViewModel.MyViewModel by lazy {
        ViewModelProvider(this).get(com.aaa.arouterone.testViewModel.MyViewModel::class.java)
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_for_view_model)
        initView()

        initData()
    }

    private fun initView() {
        tv_counts.text = vm2.counts.toString()
        btn1.setOnClickListener {
            vm2.counts++
            tv_counts.text = vm2.counts.toString()
        }
        btn2.setOnClickListener {
            vm2.counts--
            tv_counts.text = vm2.counts.toString()
        }
        btn_stop?.setOnClickListener {
//通过LiveData.setValue()/LiveData.postValue()
            //完成对ViewModel中数据的更新
            var livedata = vm2.getCurrentSecond() as MutableLiveData<Int>
            livedata.value = 0;
            //关闭定时器
            vm2.stopTiming();
        }
    }

    private fun initData() {
        /* vm2.onTimeChangeListener = object : MyViewModel.OnTimeChangeListener {
             override fun onTimerChange(second: Int) {
                 runOnUiThread {
                     tv_counts.text = second.toString()
                 }
             }
         }*/
        // 1    获取viewModel
        // 2    得到ViewModel中的LiveData
        var livedata = vm2.getCurrentSecond() as MutableLiveData<Int>
        // 3    通过liveData.observer()观察ViewModel中数据的变化
        livedata.observe(this, object : Observer<Int> {
            override fun onChanged(second: Int?) {
                Log.d("--lfc", "livedata.observe-- second: " + second.toString())
                tv_counts.text = second.toString()
            }
        })


        vm2.starttiming()
    }


}